//
//  NSFileManager+TFCore.m
//  TFFoundation
//
//  Created by TFAppleWork-Summer on 2017/3/14.
//  Copyright © 2017年 TFAppleWork-Summer. All rights reserved.
//

#import "NSFileManager+TFCore.h"

@implementation NSFileManager (TFCore)

+ (NSURL *)tf_urlForDirectory:(NSSearchPathDirectory)directory {
    return [self.defaultManager URLsForDirectory:directory inDomains:NSUserDomainMask].lastObject;
}

+ (NSString *)tf_pathForDirectory:(NSSearchPathDirectory)directory {
    return [NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES) lastObject];
}

+ (NSURL *)tf_documentURL {
    return [self tf_urlForDirectory:NSDocumentDirectory];
}

+ (NSString *)tf_documentPath {
    return [self tf_pathForDirectory:NSDocumentDirectory];
}

+ (NSURL *)tf_libraryURL {
    return [self tf_urlForDirectory:NSLibraryDirectory];
}

+ (NSString *)tf_libraryPath {
    return [self tf_pathForDirectory:NSLibraryDirectory];
}

+ (NSURL *)tf_cachesURL {
    return [self tf_urlForDirectory:NSCachesDirectory];
}

+ (NSString *)tf_cachesPath {
    return [self tf_pathForDirectory:NSCachesDirectory];
}

+ (NSInteger)tf_fileSizeAtPath:(NSString *)path {
    if ([self.defaultManager fileExistsAtPath:path]){
        return [[self.defaultManager attributesOfItemAtPath:path error:nil] fileSize];
    }
    return 0;
}

+ (double)tf_getFolderSizeWithPath:(NSString *)path {
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![self.defaultManager fileExistsAtPath:path]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:path] objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString *fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
        folderSize += [self tf_fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

+ (BOOL)tf_deleteFolderWithPath:(NSString *)path {
    NSError *error;
    NSEnumerator *childFilesEnumerator = [[self.defaultManager subpathsAtPath:path] objectEnumerator];
    NSString *fileName;
    BOOL success = NO;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString *fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
        if ([self.defaultManager removeItemAtPath:fileAbsolutePath error:&error]) {
            success = YES;
        }
    }
    return success;
}

@end
